using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Xeml.Document;

namespace Xid.Controls
{
    public partial class GermPlasmEditCtrl : UserControl, INotifyPropertyChanged
    {
        #region constructors
        public GermPlasmEditCtrl()
        {
            InitializeComponent();
            this.Validating += new CancelEventHandler(GermPlasmEditCtrl_Validating);
            binomialNames.Add("place holder", "Ph");
            // binomialNames.Add("Arabidopsis thaliana", "At");
            // binomialNames.Add("Arabidopsis halleri", "Ah");
            accessions.Add("Col-0");
            mutants.Add("unknown");
            mutants.Add("pgm");
            mutants.Add("pgm'1");
            mutants.Add("pgm'2");
            mutants.Add("pgm'3");

            transgenics.Add("unknown");
            //transgenics.Add("42");
            //transgenics.Add("0815");

            this.comboBoxBinomialName.DataSource = new BindingSource(binomialNames, null);
            this.comboBoxBinomialName.DisplayMember = "Key";
            this.comboBoxBinomialName.ValueMember = "Value";

            this.comboBoxAccession.DataSource = new BindingSource(accessions, null);
            this.comboBoxMutant.DataSource = new BindingSource(mutants, null);
            this.comboBoxTransgenic.DataSource = new BindingSource(transgenics, null);

            comboBoxBinomialName.TextChanged += new EventHandler(cBTextChanged);
            comboBoxAccession.TextChanged += new EventHandler(cBTextChanged);
            comboBoxMutant.TextChanged += new EventHandler(cBTextChanged);
            comboBoxTransgenic.TextChanged += new EventHandler(cBTextChanged);

            comboBoxBinomialName.KeyPress +=new KeyPressEventHandler(cbKeyPress);
            comboBoxAccession.KeyPress += new KeyPressEventHandler(cbKeyPress);
            comboBoxMutant.KeyPress += new KeyPressEventHandler(cbKeyPress);
            comboBoxTransgenic.KeyPress += new KeyPressEventHandler(cbKeyPress);

            comboBoxBinomialName.SelectedIndex = -1;
            comboBoxAccession.SelectedIndex = -1;
            comboBoxMutant.SelectedIndex = -1;
            comboBoxTransgenic.SelectedIndex = -1;

            this.textBoxGermPlasmId.DataBindings.Add("Text", this, "GermPlasmId", true, DataSourceUpdateMode.OnPropertyChanged);
            this.textBoxGermPlasmId.DataBindings["Text"].ControlUpdateMode = ControlUpdateMode.OnPropertyChanged;
            // this.numericUpDownPoolSize.DataBindings.Add("Value", this, "poolSize", false, DataSourceUpdateMode.OnPropertyChanged);

            this.textBoxFreeAnnotation.DataBindings.Add("Text", this, "FreeText", true, DataSourceUpdateMode.OnPropertyChanged);
            this.textBoxFreeAnnotation.DataBindings["Text"].ControlUpdateMode = ControlUpdateMode.OnPropertyChanged;

            this.textBoxNcbiTaxonId.DataBindings.Add("Text", this, "NcbiTaxonomyId", true, DataSourceUpdateMode.OnPropertyChanged);
            this.textBoxNcbiTaxonId.DataBindings["Text"].ControlUpdateMode = ControlUpdateMode.OnPropertyChanged;
        }
        #endregion constructors

        public string NcbiTaxonomyId
        {
            get { return textBoxNcbiTaxonId.Text; }
            set { textBoxNcbiTaxonId.Text = value; }
        }

        public string FreeText
        {
            get { return textBoxFreeAnnotation.Text; }
            set { textBoxFreeAnnotation.Text = value; }
        }

        private IndividualsPool _ipool;
        public IndividualsPool IndividualsPool
        {
            get { return _ipool; }
            set
            {
                _ipool = value;
                if (_ipool != null)
                    SetupGermplasmId(_ipool.GermPlasm);
            }
        }

        private string germPlasmId;
        public string GermPlasmId
        {
            get { return germPlasmId; }
            set
            {
                if (germPlasmId != value)
                {
                    germPlasmId = value;
                    //germPlasmAssigned = true;
                    OnPropertyChanged("GermPlasmId");
                }
            }
        }

        public int PoolSize { get; set; }

        private Dictionary<string, string> binomialNames = new Dictionary<string, string>();
        private List<string> accessions = new List<string>();
        private List<string> mutants = new List<string>();
        private List<string> transgenics = new List<string>();

        public void SetupGermplasmId(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                string[] x = id.Split(".".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                if (x.Length < 1)
                {
                    errorProvider.SetError(comboBoxBinomialName, "At least the species has to be defined.");
                }
                else
                {
                    for (int i = 0; i < x.Length; i++)
                    {
                        x[i] = x[i].Replace("_", string.Empty);
                    }

                    if (binomialNames.ContainsValue(x[0]))
                        comboBoxBinomialName.SelectedValue = x[0];
                    else
                        comboBoxBinomialName.Text = x[0];

                    if (x.Length >= 2)
                    {
                        comboBoxAccession.Text = x[1];
                    }
                    if (x.Length >= 3)
                    {
                        comboBoxMutant.Text = x[2];
                    }
                    if (x.Length >= 4)
                    {
                        comboBoxTransgenic.Text = x[3];
                    }
                }
            }
        }

        private void GermPlasmEditCtrl_Validating(object sender, CancelEventArgs e)
        {
            if (string.IsNullOrEmpty(comboBoxBinomialName.Text))
            {
                errorProvider.SetError(comboBoxBinomialName, "At least the species has to be defined.");
                e.Cancel = true;
            }
        }

        private void cBTextChanged(object sender, EventArgs e)
        {
            BuildId();
        }

        private void BuildId()
        {
            StringBuilder sb = new StringBuilder();

            if (binomialNames.ContainsKey(comboBoxBinomialName.Text))
                sb.Append(binomialNames[comboBoxBinomialName.Text]);
            else
                sb.Append(comboBoxBinomialName.Text);


            string subspecies = string.Empty;
            //if (accessions.Contains(comboBoxAccession.Text))
            //    subspecies = accessions.Find(delegate (string s){s ==  } [comboBoxBinomialName.Text];
            //else
            subspecies = comboBoxAccession.Text;

            string mutant = string.Empty;
            //if (mutants.Contains(comboBoxMutant.Text))
            //    mutant = mutants[comboBoxBinomialName.Text];
            //else
            mutant = comboBoxMutant.Text;

            string transgenic = string.Empty;
            //if (mutants.Contains(comboBoxMutant.Text))
            //    mutant = mutants[comboBoxBinomialName.Text];
            //else
            transgenic = comboBoxTransgenic.Text;

            if (!String.IsNullOrEmpty(subspecies))
            {
                if (subspecies == "unknown")
                    sb.AppendFormat(".{0}", "?");
                else
                    sb.AppendFormat(".{0}", subspecies);
            }

            if (!String.IsNullOrEmpty(mutant))
            {
                if (String.IsNullOrEmpty(subspecies))
                {
                    sb.AppendFormat(".{0}", "_");
                }
                if (mutant == "unknown")
                    sb.AppendFormat(".{0}", "?");
                else
                    sb.AppendFormat(".{0}", mutant);
            }

            if (!String.IsNullOrEmpty(transgenic))
            {
                if (String.IsNullOrEmpty(mutant))
                {
                    if (String.IsNullOrEmpty(subspecies))
                    {
                        sb.AppendFormat(".{0}", "_");
                    }

                    sb.AppendFormat(".{0}", "_");
                }
                if (transgenic == "unknown")
                    sb.AppendFormat(".{0}", "?");
                else
                    sb.AppendFormat(".{0}", transgenic);
            }


            textBoxGermPlasmId.Text = sb.ToString();
        }

        #region INotifyPropertyChanged Members

        protected virtual void OnPropertyChanged(string prop)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(prop));
        }
        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        private void pictureBoxAnnotatioGermPlasm_Click(object sender, EventArgs e)
        {
            using (AnnotationForm af = new AnnotationForm())
            {
                af.Setup(this._ipool, (sender as Control).Tag as string);
                af.ShowDialog(this);
            }
        }

        private void textBoxNcbiTaxonId_KeyPress(object sender, KeyPressEventArgs e)
        {
            //allow only decimal characters for NNBI Taxonomy ID reference
            e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
        }

        private void cbKeyPress(object sender, KeyPressEventArgs e)
        {
            //deny the dot (".")!
            //e.Handled = char.IsPunctuation(e.KeyChar); //thats to many
            e.Handled = e.KeyChar == '.'; //thats filters only the points out of the users input
        }
    }
}
